package com.attilax.process;

import java.lang.management.ManagementFactory;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.attilax.cmd.CmdX;
import com.attilax.io.pathx;
import com.attilax.office.OfficeCli;
import com.attilax.util.Converter;
import com.attilax.util.DateUtil;
import com.attilax.util.PropX;
import com.focustar.util.Sys;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

@SuppressWarnings("all")
//  com.attilax.process.ProcessX
public class ProcessX {
	public static final Logger logger = LoggerFactory.getLogger(ProcessX.class);

	public static void main(String[] args) {
		t2();
		System.out.println(pid());

	}
	
	
	  public static String pid()
	    {  
	        // 在windows上，获取到得name格式为 1234@userName  
	        // 1234为PID，@为分隔符，userName为当前用户  
		  //1508@Vmonkey-PC
	        String pid = ManagementFactory.getRuntimeMXBean().getName();  
	        int indexOf = pid.indexOf('@');  
	        if (indexOf > 0)  
	        {  
	            pid = pid.substring(0, indexOf);  
	        }  
	  
	        System.out.println("当前JVM Process ID: " + pid);
			return pid;  
	    }  

	private static void t2() {
		String cfg = System.getProperty("process_monitor_cfg_file", pathx.appPathV2() + "/process_monitor.txt");
		PropX px = new PropX(cfg, "gbk");
		List<Map> li = Lists.newArrayList();
		for (int i = 1; i < 10; i++) {
			String name = px.getProperty("name" + String.valueOf(i));
			String time = px.getProperty("time" + String.valueOf(i));
			if (name == null)
				continue;
			Map m = Maps.newConcurrentMap();
			m.put("name", name);
			m.put("time", time);
			li.add(m);
		}

		for (Map map : li) {
			String cmd = "wmic process   where \"name='@name@'\"  get caption,ProcessId,KernelModeTime,UserModeTime,CreationDate";

			cmd = cmd.replaceAll("@name@", map.get("name").toString());
			logger.info(cmd);

			String r = CmdX.exe_sync(cmd);

			logger.info("---cmd ret:" + r);
			long timespan_len = Converter.toLong(map.get("time"));
			List<Map> pro_li = getProcessListParse(r);
			for (Map p : pro_li) {

				Date d = DateUtil.str2date(p.get("CreationDate").toString(), true, DateUtil.fullDatetimeOrderMode);
				long CreationDate_time = d.getTime();
				long len = new Date().getTime() - CreationDate_time;
				long len_sec = len / 1000;
				p.put(" len_sec", len_sec);
				logger.info("---pro info:" + JSON.toJSONString(p));
				if (len_sec > timespan_len)

				{
					logger.info("---time out ,will be kill pro:" + JSON.toJSONString(p));
					TASKKILL_bypid(p.get("ProcessId").toString());
				}
			}

		}
	}
	public static String TASKKILL_bypid(String pid) {
		///   TASKKILL /PID 1230 /PID 1241 /PID 1253 /T
		String cmd = "TASKKILL /PID  @n@  /T";
		cmd = cmd.replaceAll("@n@", pid);
		logger.info("---cmd exe log " + cmd);
		System.out.println(cmd);
	
		String r = CmdX.exe(cmd);
		logger.info("---cmd exe ret : " + r);
		logger.info("---///cmd exe ret end");
		return r;

	}
	public static String TASKKILL(String processName) {

		String cmd = "TASKKILL /F /IM @n@  /T";
		cmd = cmd.replaceAll("@n@", processName);
		logger.info("---cmd exe log " + cmd);
		System.out.println(cmd);
	
		String r = CmdX.exe(cmd);
		logger.info("---cmd exe ret : " + r);
		logger.info("---///cmd exe ret end");
		return r;

	}

	private static List<Map> getProcessListParse(String r) {
		if (r.contains("没有可用实例") ||  r.contains("No Instance(s) Available") )
			return Lists.newArrayList();
		String[] a = r.split("\r\n");
		List<Map> li = Lists.newArrayList();
		List<Map> li_tits = Lists.newArrayList();
		for (String s : a) {
			if (s.trim().length() == 0)
				continue;
			if (s.trim().startsWith("Caption")) {
				li_tits = gettits(s.trim());
				continue;
			}
			// String[] a2 = s.split("\t");
			Map line_map = Maps.newConcurrentMap();

			// ------------set key v
			for (Map cur_tit : li_tits) {
				// String cur_tit_val=
				String cur_tit_val = s.substring(Converter.toInt(cur_tit.get("startIdx")),
						Converter.toInt(cur_tit.get("endIdx")));
				line_map.put(cur_tit.get("name"), cur_tit_val);

				// line_map.put("CreationDate", CreationDate);
				//
			}
			line_map.put("CreationDate_sec", getCreationDateSec(line_map.get("CreationDate").toString()));
			li.add(line_map);

		}
		return li;
	}

	private static Object getCreationDateSec(String creationDate) {
		int dot_pos = creationDate.indexOf(".");
		if (dot_pos == -1)
			return creationDate;
		return creationDate.substring(0, dot_pos);
	}

	private static List<Map> gettits(String s) {
		String trim = s.trim();
		for (int i = 0; i < 10; i++) {
			trim = trim.replaceAll("  ", " ");
		}
		String[] a = trim.split(" ");
		List<Map> li = Lists.newArrayList();
		int n = 0;
		for (String tit : a) {
			Map m = Maps.newConcurrentMap();
			m.put("name", tit);
			int pos = s.indexOf(tit);
			m.put("startIdx", pos);
			String nextTit;
			try {
				nextTit = a[n + 1];
			} catch (ArrayIndexOutOfBoundsException e) {
				continue;
			}

			int pos_next = s.indexOf(nextTit);
			int pos_end = pos_next;
			m.put("endIdx", pos_next);
			li.add(m);
			n++;
		}
		return li;
	}

}
